﻿using LHJ.Common.Dto;
using LHJ.Common.Extend;
using LHJ.Common.Tools;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace yysAuxiliary
{
    public partial class AuthFrm : Form
    {
        public AuthFrm()
        {
            InitializeComponent();
        }

        private void AuthFrm_Load(object sender, EventArgs e)
        {
            txtMachineCode.Text = MachineCode.GetMachineCodeString().ToBase64Str();
            txtCode.Text = ConfigData.Current.AuthCode;
            if (GetAuth().isAuth)
                this.DialogResult = DialogResult.OK;
        }

        /// <summary>
        /// 授权
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExperience_Click(object sender, EventArgs e)
        {
            var result = GetAuth();
            if (result.isAuth)
            {
                ConfigData.Current.AuthCode = txtCode.Text.Trim();
                ConfigData.Current.WriteJson();
                this.DialogResult = DialogResult.OK;
            }
            else
                MessageBox.Show(result.msg);
        }


        private (bool isAuth, string msg) GetAuth()
        {
            try
            {
                var str = RSAHelper.RSADecrypt(txtCode.Text.Trim(), Data.prikey);
                var dto = JsonConvert.DeserializeObject<AuthInfo>(str);
                if (DateTimeExtend.GetNetDateTime() >= dto.ExpiryDate)
                    return (false, "当前授权已过期，请联系作者");
                if (dto.MachineCode != txtMachineCode.Text)
                    return (false, "当前授权码不对应当前机器，请联系作者");
                Data.AuthExpireTime = dto.ExpiryDate;
                return (true, "");
            }
            catch (Exception ex)
            {
                return (false, "授权码错误,请联系作者");
            }
        }

    }
}
